package com.ray.controller;


import com.ray.entity.Account;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ray
 * @since 2020-12-01
 */
@Controller
public class AccountController {

    @GetMapping("/{url}")
    public String redirect(@PathVariable("url")String url){
        return url;
    }

    /**
     * 登录
     * form表单提交不能用restful
     *
     */
    @PostMapping("login")
    public String login(String username, String password, Model model){
        //subject与shiro进行交互
        Subject subject = SecurityUtils.getSubject();
        //token封装用户信息
        UsernamePasswordToken toekn = new UsernamePasswordToken(username, password);
        //shiro开始登录验证
        try {
            subject.login(toekn);
            Account account = (Account)subject.getPrincipal();
            subject.getSession().setAttribute("account", account);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不正确");
            return "login";
        }
    }

    @GetMapping("/unauth")
    @ResponseBody
    public String unauth(){
        return "权限不足";
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @RequiresPermissions("user:add")
    @GetMapping("/user/add")
    @ResponseBody
    public String add(){
        return "ADD";
    }

}
